package yf.mall.controller.api.app;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.yf.annotation.IgnoreAuth;
import com.yf.annotation.LoginUserId;
import com.yf.response.R;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import yf.mall.common.Const;
import yf.mall.component.app.AppCourseComponent;
import yf.mall.entity.AppCategoryEntity;
import yf.mall.entity.AppCoursePurchaseEntity;
import yf.mall.entity.AppCoursePurchaseEntityExample;
import yf.mall.entity.UserEntity;
import yf.mall.enums.app.AppBehaviorTypeEnum;
import yf.mall.enums.app.AppCategoryTypeEnum;
import yf.mall.service.app.AppBehaviorService;
import yf.mall.service.app.AppCategoryService;
import yf.mall.service.app.AppCoursePurchaseService;
import yf.mall.vo.app.common.ClassificationVo;
import yf.mall.vo.app.common.ListQuery;
import yf.mall.vo.app.course.AppCoursePurchaseVo;
import yf.mall.vo.app.request.CommonRequest;
import yf.mall.vo.app.common.ListResult;
import yf.mall.vo.app.course.AppCourseVo;
import yf.mall.vo.app.request.CourseListRequest;
import yf.mall.vo.app.request.CourseReportRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/api/app/mini/course")
public class ApiAppCourseController extends ApiAppBaseController {

    @Resource
    private AppCourseComponent appCourseComponent;

    @Resource
    private AppCategoryService appCategoryService;

    @Resource
    private AppBehaviorService appBehaviorService;

    @Resource
    private AppCoursePurchaseService appCoursePurchaseService;


    /**
     * POST /api/app/mini/course/classification : 课程分类
     */
    @RequestMapping(value = "/classification",
            method = RequestMethod.POST)
    @IgnoreAuth
    public R appCourseClassification() {
        AppCategoryEntity rootCategory = appCategoryService.getRootCategory(AppCategoryTypeEnum.COURSE_ROOT.getType());
        if (rootCategory == null) {
            return R.ok(Collections.emptyList());
        }
        List<AppCategoryEntity> appCategoryEntities = appCategoryService.getCategoryByParent(rootCategory.getType(), rootCategory.getRootId());
        return dataResult(appCategoryEntities.stream().map(ClassificationVo::build).collect(Collectors.toList()));
    }


    /**
     * POST /api/app/mini/course/detail : 课程详情
     */
    @RequestMapping(value = "/detail",
            method = RequestMethod.POST)
    @IgnoreAuth
    public R appCourseDetail(HttpServletRequest request, @RequestBody CommonRequest commonRequest) {
        Long courseId = commonRequest.getId();
        Long loginUserId = getLoginUser(request);
        Long userLevel = getUserLevel(loginUserId);
        AppCourseVo appCourseVo = appCourseComponent.getDouxinCourseVo(courseId);
        if (appCourseVo.getLevelId() < userLevel) {
            // 用户访问数据级别大于课程级别的才能访问
            return R.error("该课程为付费课程，需登录后，兑换才能访问");
        }
        return dataResult(appCourseVo);

    }


    /**
     * POST /api/app/mini/course/list : 课程列表
     */
    @RequestMapping(value = "/list",
            method = RequestMethod.POST)
    @IgnoreAuth
    public R appCourseList(HttpServletRequest request, @Valid @RequestBody(required = true) CourseListRequest courseListRequest) {
        Long loginUserId = getLoginUser(request);
        //TODO 这里是根据level_id判断大小的 后面根据可能要改成lv
        courseListRequest.setLevelId(getUserLevel(loginUserId));
        ListResult<AppCourseVo> courseList = appCourseComponent.getCourseList(loginUserId, courseListRequest);
        return dataResult(courseList);
    }

    /**
     * POST /api/app/mini/course/report-schedule : 课程进度上报
     */
    @RequestMapping(value = "/report-schedule",
            method = RequestMethod.POST)
    public R appCourseReportSchedule(@LoginUserId Long userId, @Valid @RequestBody(required = true) CourseReportRequest courseReportRequest) {
        // TODO 记录上报日志
        Long refId;
        if (courseReportRequest == null) {
            return R.error("上报日志信息为空");
        }
        if (courseReportRequest.getId() == null) {
            return R.error("上报日志主体为空");
        }
        refId = ObjectUtils.defaultIfNull(courseReportRequest.getItemId(), courseReportRequest.getId());
        if (courseReportRequest.getTimes() == null) {
            return R.error("课程上报的时长信息为空");
        }
        String behavior = "用户观看课程视频，已累计观看" + convertToChineseTime(courseReportRequest.getTimes().intValue());
        appBehaviorService.record(userId, refId, AppBehaviorTypeEnum.WATCH_COURSE.getKey(), behavior, 10);
        return R.ok();
    }

    private static String convertToChineseTime(int seconds) {
        if (seconds < 0) {
            throw new IllegalArgumentException("秒数不能为负数");
        }

        int hours = seconds / 3600;
        int minutes = (seconds % 3600) / 60;
        int remainingSeconds = seconds % 60;

        if (hours > 0) {
            return MessageFormat.format("{0}小时{1}分钟{2}秒", hours, minutes, remainingSeconds);
        } else if (minutes > 0) {
            return MessageFormat.format("{0}分钟{1}秒", minutes, remainingSeconds);
        } else {
            return MessageFormat.format("{0}秒", remainingSeconds);
        }
    }

    /**
     * POST /api/app/mini/index/purchase/list : app购买记录
     *
     * @return
     */
    @RequestMapping("/index/purchase/list")
    @IgnoreAuth
    public R appCoursePurchaseList(HttpServletRequest request, @RequestBody ListQuery listQuery) {
        Long loginUserId = getLoginUser(request);
        AppCoursePurchaseEntityExample example = new AppCoursePurchaseEntityExample();
        example.createCriteria().andUserIdEqualTo(loginUserId);
        PageInfo<AppCoursePurchaseEntity> page = appCoursePurchaseService.page(example, new Page<>(listQuery.getPage(), listQuery.getLimit()));
        List<AppCoursePurchaseVo> appCoursePurchaseVos = page.getList().stream().map(entity -> {
            AppCoursePurchaseVo appCoursePurchaseVo = new AppCoursePurchaseVo();
            appCoursePurchaseVo.setActiveCode(entity.getActiveCode());
            appCoursePurchaseVo.setActiveStatus(entity.getActiveStatus());
            appCoursePurchaseVo.setActiveStatusStr(Objects.equals(1, entity.getActiveStatus()) ? "已激活" : "待激活");
            appCoursePurchaseVo.setActiveTime(entity.getActiveTime());
            appCoursePurchaseVo.setCover(entity.getCover());
            appCoursePurchaseVo.setId(entity.getId());
            appCoursePurchaseVo.setOrderId(entity.getOrderId());
            appCoursePurchaseVo.setShotCount(entity.getShotCount());
            appCoursePurchaseVo.setTitle(entity.getTitle());
            return appCoursePurchaseVo;
        }).collect(Collectors.toList());
        return dataResult(new ListResult<>(appCoursePurchaseVos, page.isHasNextPage()));
    }

    private Long getUserLevel(Long loginUserId) {
        if (loginUserId == null) {
            return Const.DEFUALT_VISTOR_LEVEL;
        } else {
            UserEntity userEntity = getLoginUser(loginUserId);
            if (userEntity == null) {
                return Const.DEFUALT_VISTOR_LEVEL;
            }
            return userEntity.getLevelId();
        }
    }
}
